﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LandLordNeedsManualLaborersIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LandLordNeedsManualLaborersIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency NeedsLaborersIssueFrequency = IssueBase.IssueFrequency.VeryCommon;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      if (issueGiver.CurrentSettlement == null || !issueGiver.IsRuralNotable || issueGiver.GetTraitLevel(DefaultTraits.Mercy) > 0)
        return false;
      Village village = issueGiver.CurrentSettlement.Village;
      if (village == null)
        return false;
      return village.VillageType == DefaultVillageTypes.IronMine || village.VillageType == DefaultVillageTypes.ClayMine || village.VillageType == DefaultVillageTypes.SaltMine || village.VillageType == DefaultVillageTypes.SilverMine;
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnSelected), typeof (LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssue), IssueBase.IssueFrequency.VeryCommon));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private IssueBase OnSelected(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssue(issueOwner);
    }

    public class LandLordNeedsManualLaborersIssue : IssueBase
    {
      private const int IssueDuration = 30;
      private const int QuestDuration = 20;
      private const int AlternativeSolutionTroopTierRequirement = 2;
      private const int CompanionRequiredSkillLevel = 120;

      internal static void AutoGeneratedStaticCollectObjectsLandLordNeedsManualLaborersIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get => IssueBase.AlternativeSolutionScaleFlag.RequiredTroops;
      }

      private int RequestedPrisonerCount => 6 + MathF.Ceiling(30f * this.IssueDifficultyMultiplier);

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 8 + MathF.Ceiling(12f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 5 + MathF.Ceiling(5f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold => this.RequestedPrisonerCount * 50;

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return this.IssueOwner.CharacterObject.GetTraitLevel(DefaultTraits.Mercy) >= 0 ? new TextObject("{=1LFcSRPw}I have a mine near here. We had an unfortunate accident a week back. Two workers were crushed to death. It's a great shame... but work must go on. Trouble is, no one wants to come back. If perhaps you could find me some prisoners...[if:convo_thinking][ib:hip]") : new TextObject("{=QEhapwtN}I own a mine near here. Normally I can find willing villagers to work it, but these days they've been demanding higher and higher wages. Fine. They're out of a job, but I still need to work the mine. If you could perhaps find me some prisoners...[if:convo_normal][ib:confident2]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=DSMMIrz9}Prisoners... You want criminals or war captives?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=ji5kkqXy}They need to be criminals, bandits, for me to do this legally. I need at least {WANTED_PRISONER_AMOUNT} of them. But if you can bring more I will gladly accept. I'm willing to pay ten times more than their market price for each. What do you say?[if:convo_nonchalant]");
          explanationByIssueGiver.SetTextVariable("WANTED_PRISONER_AMOUNT", this.RequestedPrisonerCount);
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=WpidwcAV}If you have a companion who understands this type of work and {ALTERNATIVE_TROOP_AMOUNT} men, I can tell them where to go to get their hands on some prisoners.");
          explanationByIssueGiver.SetTextVariable("ALTERNATIVE_TROOP_AMOUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=C06TxxnM}I'll bring you at least {WANTED_PRISONER_AMOUNT} prisoners as soon as possible.");
          solutionAcceptByPlayer.SetTextVariable("WANTED_PRISONER_AMOUNT", this.RequestedPrisonerCount);
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get => new TextObject("{=QH3shVzb}My people can bring you your laborers.");
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=XXOlu6z0}Thank you for sparing some of your men to save my business. I am looking forward to resuming work.[if:convo_mocking_teasing]");
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get => new TextObject("{=PrzguaEq}Thank you. I appreciate your people's help.");
      }

      public override bool IsThereAlternativeSolution => true;

      public override bool IsThereLordSolution => false;

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=MYeCnHTb}You asked {COMPANION.LINK} to deliver at least {WANTED_PRISONER_AMOUNT} prisoners to {ISSUE_GIVER.LINK} in {SETTLEMENT}. They should rejoin your party in {RETURN_DAYS} days.");
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("WANTED_PRISONER_AMOUNT", this.RequestedPrisonerCount);
          parent.SetTextVariable("SETTLEMENT", this.IssueOwner.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          return parent;
        }
      }

      public override TextObject Title
      {
        get => new TextObject("{=hVIsGd2y}Landowner Needs Manual Laborers");
      }

      public override TextObject Description
      {
        get
        {
          TextObject description = new TextObject("{=5of4a1kg}A landowner needs your help to find prisoners to use in {?ISSUE_GIVER.GENDER}her{?}his{\\?} mines as manual laborers.");
          StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject);
          return description;
        }
      }

      public LandLordNeedsManualLaborersIssue(Hero issueOwner)
        : base(issueOwner, CampaignTime.DaysFromNow(30f))
      {
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        if (issueEffect == DefaultIssueEffects.VillageHearth)
          return -0.3f;
        return issueEffect == DefaultIssueEffects.IssueOwnerPower ? -0.1f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Athletics) >= hero.GetSkillValue(DefaultSkills.Leadership) ? DefaultSkills.Athletics : DefaultSkills.Leadership, 120);
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool IsTroopTypeNeededByAlternativeSolution(CharacterObject character)
      {
        return character.Tier >= 2;
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      public override bool IssueStayAliveConditions()
      {
        return !this.IssueOwner.CurrentSettlement.IsRaided && !this.IssueOwner.CurrentSettlement.IsUnderRaid;
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flags,
        out Hero relationHero,
        out SkillObject skill)
      {
        flags = IssueBase.PreconditionFlags.None;
        relationHero = (Hero) null;
        skill = (SkillObject) null;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flags |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (FactionManager.IsAtWarAgainstFaction(issueGiver.MapFaction, Hero.MainHero.MapFaction))
          flags |= IssueBase.PreconditionFlags.AtWar;
        return flags == IssueBase.PreconditionFlags.None;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(20f), this.RequestedPrisonerCount);
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (500.0 + 700.0 * (double) this.IssueDifficultyMultiplier);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.IssueOwner, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 30)
        });
        this.IssueOwner.AddPower(10f);
        this.RelationshipChangeWithIssueOwner = 5;
      }
    }

    public class LandLordNeedsManualLaborersIssueQuest : QuestBase
    {
      private const int MaximumPrisonerLimitMinValue = 40;
      private const int MaximumPrisonerLimitMaxValue = 60;
      [SaveableField(1)]
      private int _requestedPrisonerCount;
      [SaveableField(2)]
      private bool _shareProfit;
      [SaveableField(4)]
      private bool _counterOfferGiven;
      [SaveableField(5)]
      private int _deliveredPrisonerCount;
      [SaveableField(6)]
      private int _rewardGold;
      [SaveableField(8)]
      private int _maximumPrisonerCount;
      [SaveableField(9)]
      private bool _playerReachedMaximumAmount;
      [SaveableField(7)]
      private JournalLog _questProgressLogTest;

      internal static void AutoGeneratedStaticCollectObjectsLandLordNeedsManualLaborersIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._questProgressLogTest);
      }

      internal static object AutoGeneratedGetMemberValue_requestedPrisonerCount(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._requestedPrisonerCount;
      }

      internal static object AutoGeneratedGetMemberValue_shareProfit(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._shareProfit;
      }

      internal static object AutoGeneratedGetMemberValue_counterOfferGiven(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._counterOfferGiven;
      }

      internal static object AutoGeneratedGetMemberValue_deliveredPrisonerCount(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._deliveredPrisonerCount;
      }

      internal static object AutoGeneratedGetMemberValue_rewardGold(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._rewardGold;
      }

      internal static object AutoGeneratedGetMemberValue_maximumPrisonerCount(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._maximumPrisonerCount;
      }

      internal static object AutoGeneratedGetMemberValue_playerReachedMaximumAmount(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._playerReachedMaximumAmount;
      }

      internal static object AutoGeneratedGetMemberValue_questProgressLogTest(object o)
      {
        return (object) ((LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest) o)._questProgressLogTest;
      }

      public override TextObject Title
      {
        get => new TextObject("{=hVIsGd2y}Landowner Needs Manual Laborers");
      }

      public override bool IsRemainingTimeHidden => false;

      private bool IsQuestWithCounterOffer
      {
        get
        {
          return this.QuestGiver.CharacterObject.GetTraitLevel(DefaultTraits.Mercy) < 0 && this.QuestGiver.CurrentSettlement.Notables.FirstOrDefault<Hero>((Func<Hero, bool>) (x => x.IsHeadman)) != null;
        }
      }

      private TextObject QuestStartedLogText
      {
        get
        {
          TextObject parent = new TextObject("{=7XR4MJci}{QUEST_GIVER.LINK}, a landowner in {SETTLEMENT}, told you that {?QUEST_GIVER.GENDER}she{?}he{\\?} needs prisoners to use in {?QUEST_GIVER.GENDER}her{?}his{\\?} mines as manual laborers. {?QUEST_GIVER.GENDER}She{?}He{\\?} asked you to bring at least {NEEDED_PRISONER_AMOUNT} bandit prisoners, but {?QUEST_GIVER.GENDER}she{?}he{\\?} will pay extra if you bring more. You have agreed to bring {?QUEST_GIVER.GENDER}her{?}him{\\?} at least {NEEDED_PRISONER_AMOUNT} bandit prisoner and you will be paid ten times more than their market price for each prisoner you bring.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("SETTLEMENT", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("NEEDED_PRISONER_AMOUNT", this._requestedPrisonerCount);
          return parent;
        }
      }

      private TextObject QuestCanceledWarDeclaredLog
      {
        get
        {
          TextObject parent = new TextObject("{=vW6kBki9}Your clan is now at war with {QUEST_GIVER.LINK}'s realm. Your agreement with {QUEST_GIVER.LINK} is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestGiverVillageRaided
      {
        get
        {
          TextObject parent = new TextObject("{=gJG0xmAq}{QUEST_GIVER.LINK}'s village {QUEST_SETTLEMENT} was raided. Your agreement with {QUEST_GIVER.LINK} is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_SETTLEMENT", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          return parent;
        }
      }

      private TextObject QuestSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=ucu9u1nS}You delivered the prisoners to {QUEST_GIVER.LINK} as promised.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerSharedTheProfitWithHeadManLogText
      {
        get
        {
          return new TextObject("{=ULpP07bg}You promised to share half of the profit with the headman and the villager.");
        }
      }

      private TextObject QuestSuccessWithProfitShareLog
      {
        get
        {
          TextObject parent = new TextObject("{=SyuxD1aY}You delivered the prisoners to {QUEST_GIVER.LINK} as promised and you shared half of the profit with the headman and the villagers.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestFailPlayerAcceptedCounterOfferLog
      {
        get
        {
          TextObject parent = new TextObject("{=u8DJ8a2D}You agreed with the headman to break your agreement with {QUEST_GIVER.LINK}. By doing so you protected the villagers' jobs and now they are grateful to you.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestFailedWithTimeOutLogText
      {
        get
        {
          TextObject parent = new TextObject("{=b1lsZNxE}You failed to deliver enough prisoners in time. {QUEST_GIVER.LINK} must be disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      public LandLordNeedsManualLaborersIssueQuest(
        string questId,
        Hero giverHero,
        CampaignTime duration,
        int requestedPrisonerCount)
        : base(questId, giverHero, duration, 0)
      {
        this._requestedPrisonerCount = requestedPrisonerCount;
        this._shareProfit = false;
        this._deliveredPrisonerCount = 0;
        this._rewardGold = 0;
        this._counterOfferGiven = false;
        this._maximumPrisonerCount = MBRandom.RandomInt(40, 60);
        this._playerReachedMaximumAmount = false;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddTrackedObject((ITrackableCampaignObject) this.QuestGiver.CurrentSettlement);
        TextObject taskName = new TextObject("{=N4eLGduQ}Delivered Prisoners ({TOTAL_REWARD}{GOLD_ICON})");
        taskName.SetTextVariable("TOTAL_REWARD", this._rewardGold);
        taskName.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        this._questProgressLogTest = this.AddDiscreteLog(this.QuestStartedLogText, taskName, this._deliveredPrisonerCount, this._requestedPrisonerCount);
      }

      private DialogFlow GetCounterOfferDialogFlow()
      {
        TextObject textObject1 = new TextObject("{=aJHMafam}{?PLAYER.GENDER}Madam{?}Sir{\\?} - a moment of your time! [if:convo_undecided_open][ib:nervous2]You're on a job for {ISSUE_GIVER.LINK}, am I right? Look - our people are depending on those jobs. {?ISSUE_GIVER.GENDER}She{?}He{\\?} doesn't need to pay us a living wage if {?ISSUE_GIVER.GENDER}she{?}he{\\?} can do the work with prisoners. Please - break your agreement. You don't have to do this.");
        StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, textObject1);
        StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.QuestGiver.CharacterObject, textObject1);
        TextObject textObject2 = new TextObject("{=8BdJ2MZj}I don't want to hurt your people. I'll forget my deal with {ISSUE_GIVER.LINK}.");
        StringHelpers.SetCharacterProperties("ISSUE_GIVER", this.QuestGiver.CharacterObject, textObject2);
        return DialogFlow.CreateDialogFlow("start", 125).NpcLine(textObject1).Condition((ConversationSentence.OnConditionDelegate) (() => !this._counterOfferGiven && Hero.OneToOneConversationHero != null && Hero.OneToOneConversationHero == this.QuestGiver.CurrentSettlement.Notables.FirstOrDefault<Hero>((Func<Hero, bool>) (x => x.IsHeadman)))).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this._counterOfferGiven = true)).BeginPlayerOptions().PlayerOption("{=rOWyAHPo}Mind your own business, Headman.").NpcLine("{=tLapkQqg}We won't forget this![if:convo_thinking][ib:aggressive]").Consequence((ConversationSentence.OnConsequenceDelegate) (() => ChangeRelationAction.ApplyPlayerRelation(Hero.OneToOneConversationHero, -3))).CloseDialog().PlayerOption("{=I3GUAb9a}I understand your concern, Headman, but I made an agreement. How about I share the profit with you and your people?").NpcLine("{=MmQt0TD3}This is not we want, but it's more than nothing.[if:convo_dismayed][ib:normal]").Consequence(new ConversationSentence.OnConsequenceDelegate(this.ShareTheProfit)).CloseDialog().PlayerOption(textObject2).NpcLine("{=E5yAFR6y}Good to hear that. Thank you.[if:convo_relaxed_happy][ib:normal]").Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestFailPlayerAcceptedCounterOffer)).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void ShareTheProfit()
      {
        this.AddLog(this.PlayerSharedTheProfitWithHeadManLogText);
        ChangeRelationAction.ApplyPlayerRelation(Hero.OneToOneConversationHero, 3);
        this._shareProfit = true;
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=l7dL6arZ}Thank you. Remember - they need to be looters or bandits. Anyone else I can't put to work.[if:convo_mocking_teasing][ib:closed]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        TextObject npcDiscussLine = new TextObject("{=!}{MANUAL_LABORERS_QUEST_NOTABLE_DISCUSS}");
        TextObject npcResponseLine = new TextObject("{=!}{MANUAL_LABORERS_QUEST_NOTABLE_RESPONSE}");
        bool changeDialogAfterTransfer = false;
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").BeginNpcOptions().NpcOption(new TextObject("{=VRLbAaYe}Thank you for saving my business {?PLAYER.GENDER}madam{?}sir{\\?}. Here is your payment."), (ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver && this._playerReachedMaximumAmount)).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          this.ApplyQuestSuccessConsequences();
          this.CompleteQuestWithSuccess();
        })).CloseDialog().NpcOption(npcDiscussLine, (ConversationSentence.OnConditionDelegate) (() =>
        {
          if (Hero.OneToOneConversationHero != this.QuestGiver)
            return false;
          if (!changeDialogAfterTransfer)
          {
            npcDiscussLine.SetTextVariable("MANUAL_LABORERS_QUEST_NOTABLE_DISCUSS", new TextObject("{=B0YOpGsZ}Any news about my prisoners?[if:convo_mocking_teasing][ib:hip]"));
          }
          else
          {
            npcDiscussLine.SetTextVariable("MANUAL_LABORERS_QUEST_NOTABLE_DISCUSS", new TextObject("{=ds294zxi}Anything else?"));
            changeDialogAfterTransfer = false;
          }
          return true;
        })).BeginPlayerOptions().PlayerOption(new TextObject("{=QbaOoilS}Yes, I have brought you a few men.")).Condition((ConversationSentence.OnConditionDelegate) (() => this.CheckIfThereIsSuitablePrisonerInPlayer() && !this._playerReachedMaximumAmount)).NpcLine(npcResponseLine).Condition((ConversationSentence.OnConditionDelegate) (() =>
        {
          if (this._playerReachedMaximumAmount)
            return false;
          if ((double) this._deliveredPrisonerCount < (double) this._maximumPrisonerCount * 0.75)
          {
            npcResponseLine.SetTextVariable("MANUAL_LABORERS_QUEST_NOTABLE_RESPONSE", new TextObject("{=0ewaZnfe}Very good. Keep them coming.[if:convo_mocking_aristocratic]"));
          }
          else
          {
            TextObject variable = new TextObject("{=CBBPWMZd}Thanks to you, my mines are full {?PLAYER.GENDER}madam{?}sir{\\?}. I will only buy {X} more then we're done.");
            variable.SetTextVariable("X", this._maximumPrisonerCount - this._deliveredPrisonerCount);
            npcResponseLine.SetTextVariable("MANUAL_LABORERS_QUEST_NOTABLE_RESPONSE", variable);
            changeDialogAfterTransfer = false;
          }
          return true;
        })).PlayerLine(new TextObject("{=IULW8h03}Sure.")).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          changeDialogAfterTransfer = true;
          this.OpenPrisonerDeliveryScreen();
        })).NpcLine(new TextObject("{=!}Party screen goes here.")).GotoDialogState("quest_discuss").PlayerOption(new TextObject("{=UOE7ejgq}Here is all I've got. Let's settle up and finish this business.")).Condition((ConversationSentence.OnConditionDelegate) (() => !this._playerReachedMaximumAmount && this._deliveredPrisonerCount >= this._requestedPrisonerCount)).NpcLine(new TextObject("{=YZ6UmX5o}Certainly. Here is your payment as I promised. Thank you.[if:convo_mocking_teasing][ib:confident3]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() =>
        {
          this.ApplyQuestSuccessConsequences();
          this.CompleteQuestWithSuccess();
        })).CloseDialog().PlayerOption(new TextObject("{=wErSpkjy}I'm still working on it.")).NpcLine(new TextObject("{=oiLdjqwe}I am glad to hear that.[if:convo_nonchalant]")).CloseDialog().EndPlayerOptions();
        if (!this.IsQuestWithCounterOffer)
          return;
        this.QuestCharacterDialogFlow = this.GetCounterOfferDialogFlow();
      }

      private void OpenPrisonerDeliveryScreen()
      {
        PartyScreenManager.OpenScreenWithCondition(new IsTroopTransferableDelegate(this.IsTroopTransferable), new PartyPresentationDoneButtonConditionDelegate(this.DoneButtonCondition), new PartyPresentationDoneButtonDelegate(this.OnDoneClicked), new PartyPresentationCancelButtonDelegate(this.OnCancelClicked), PartyScreenLogic.TransferState.NotTransferable, PartyScreenLogic.TransferState.Transferable, this.QuestGiver.Name, 150, false, false, PartyScreenMode.PrisonerManage);
      }

      private void OnCancelClicked() => Campaign.Current.ConversationManager.ContinueConversation();

      private Tuple<bool, TextObject> DoneButtonCondition(
        TroopRoster leftMemberRoster,
        TroopRoster leftPrisonRoster,
        TroopRoster rightMemberRoster,
        TroopRoster rightPrisonRoster,
        int leftLimitNum,
        int rightLimitNum)
      {
        if (this._maximumPrisonerCount - this._deliveredPrisonerCount >= leftPrisonRoster.TotalManCount)
          return new Tuple<bool, TextObject>(true, (TextObject) null);
        int variable = this._maximumPrisonerCount - this._deliveredPrisonerCount;
        TextObject textObject = new TextObject("{=bgXebaRF}You can only transfer {X} prisoner{?IS_PLURAL}s{?}{\\?}.");
        textObject.SetTextVariable("IS_PLURAL", variable > 1 ? 1 : 0);
        textObject.SetTextVariable("X", variable);
        return new Tuple<bool, TextObject>(false, textObject);
      }

      private bool OnDoneClicked(
        TroopRoster leftMemberRoster,
        TroopRoster leftPrisonRoster,
        TroopRoster rightMemberRoster,
        TroopRoster rightPrisonRoster,
        FlattenedTroopRoster takenPrisonerRoster,
        FlattenedTroopRoster releasedPrisonerRoster,
        bool isForced,
        PartyBase leftParty,
        PartyBase rightParty)
      {
        foreach (TroopRosterElement troopRosterElement in (List<TroopRosterElement>) leftPrisonRoster.GetTroopRoster())
        {
          this._rewardGold += Campaign.Current.Models.RansomValueCalculationModel.PrisonerRansomValue(troopRosterElement.Character, Hero.MainHero) * troopRosterElement.Number * 5;
          this._deliveredPrisonerCount += troopRosterElement.Number;
        }
        this._questProgressLogTest.UpdateCurrentProgress(this._deliveredPrisonerCount);
        this._questProgressLogTest.TaskName.SetTextVariable("TOTAL_REWARD", this._rewardGold);
        if (this._deliveredPrisonerCount == this._maximumPrisonerCount)
          this._playerReachedMaximumAmount = true;
        Campaign.Current.ConversationManager.ContinueConversation();
        return true;
      }

      private bool IsTroopTransferable(
        CharacterObject character,
        PartyScreenLogic.TroopType type,
        PartyScreenLogic.PartyRosterSide side,
        PartyBase leftOwnerParty)
      {
        if (side == PartyScreenLogic.PartyRosterSide.Left)
          return true;
        return this._maximumPrisonerCount - this._deliveredPrisonerCount >= 0 && MobileParty.MainParty.PrisonRoster.Contains(character) && character.Occupation == Occupation.Bandit;
      }

      private bool CheckIfThereIsSuitablePrisonerInPlayer()
      {
        bool flag = false;
        foreach (TroopRosterElement troopRosterElement in (List<TroopRosterElement>) MobileParty.MainParty.PrisonRoster.GetTroopRoster())
        {
          if (troopRosterElement.Character.Occupation == Occupation.Bandit)
          {
            flag = true;
            break;
          }
        }
        return flag;
      }

      private void ApplyQuestSuccessConsequences()
      {
        if (this._shareProfit)
        {
          this.AddLog(this.QuestSuccessWithProfitShareLog);
          TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
          {
            new Tuple<TraitObject, int>(DefaultTraits.Honor, 30)
          });
          GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this._rewardGold / 2);
          if (this.IsQuestWithCounterOffer)
            this.QuestGiver.CurrentSettlement.Notables.First<Hero>((Func<Hero, bool>) (x => x.IsHeadman)).AddPower(5f);
        }
        else
        {
          this.AddLog(this.QuestSuccessLog);
          TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[2]
          {
            new Tuple<TraitObject, int>(DefaultTraits.Honor, 30),
            new Tuple<TraitObject, int>(DefaultTraits.Mercy, -20)
          });
          GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this._rewardGold);
          if (this.IsQuestWithCounterOffer && this._counterOfferGiven)
          {
            ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver.CurrentSettlement.Notables.First<Hero>((Func<Hero, bool>) (x => x.IsHeadman)), -5);
            this.QuestGiver.CurrentSettlement.Notables.First<Hero>((Func<Hero, bool>) (x => x.IsHeadman)).AddPower(-10f);
          }
        }
        this.QuestGiver.AddPower(10f);
        this.RelationshipChangeWithQuestGiver = 5;
      }

      private void QuestFailPlayerAcceptedCounterOffer()
      {
        this.AddLog(this.QuestFailPlayerAcceptedCounterOfferLog);
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[3]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Mercy, 20),
          new Tuple<TraitObject, int>(DefaultTraits.Generosity, 20),
          new Tuple<TraitObject, int>(DefaultTraits.Honor, -10)
        });
        this.QuestGiver.AddPower(-10f);
        this.RelationshipChangeWithQuestGiver = -3;
        Hero gainedRelationWith = this.QuestGiver.CurrentSettlement.Notables.First<Hero>((Func<Hero, bool>) (x => x.IsHeadman));
        gainedRelationWith.AddPower(10f);
        ChangeRelationAction.ApplyPlayerRelation(gainedRelationWith, 5);
        this.CompleteQuestWithFail();
      }

      protected override void OnBeforeTimedOut(
        ref bool completeWithSuccess,
        ref bool doNotResolveTheQuest)
      {
        if (this._deliveredPrisonerCount < this._requestedPrisonerCount)
          return;
        completeWithSuccess = true;
        this.ApplyQuestSuccessConsequences();
      }

      protected override void OnTimedOut()
      {
        this.AddLog(this.QuestFailedWithTimeOutLogText);
        this.QuestGiver.AddPower(-10f);
        this.RelationshipChangeWithQuestGiver = -5;
      }

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.VillageBeingRaided.AddNonSerializedListener((object) this, new Action<Village>(this.OnVillageRaided));
        CampaignEvents.GameMenuOpened.AddNonSerializedListener((object) this, new Action<MenuCallbackArgs>(this.OnGameMenuOpened));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
          return;
        QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
      }

      private void OnGameMenuOpened(MenuCallbackArgs args)
      {
        if (!this.IsQuestWithCounterOffer || this._counterOfferGiven || !(args.MenuContext.GameMenu.StringId == "village") || Settlement.CurrentSettlement != this.QuestGiver.CurrentSettlement || Campaign.Current.GameMenuManager.NextLocation != null || !(GameStateManager.Current.ActiveState is MapState) || PlayerEncounter.EncounterSettlement == null || !this.CheckIfThereIsSuitablePrisonerInPlayer())
          return;
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter, PartyBase.MainParty), new ConversationCharacterData(this.QuestGiver.CurrentSettlement.Notables.First<Hero>((Func<Hero, bool>) (x => x.IsHeadman)).CharacterObject));
      }

      private void OnVillageRaided(Village village)
      {
        if (village != this.QuestGiver.CurrentSettlement.Village)
          return;
        this.AddLog(this.QuestGiverVillageRaided);
        this.CompleteQuestWithCancel();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.CurrentSettlement.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this.QuestCanceledWarDeclaredLog);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this.PlayerDeclaredWarQuestLogText, this.QuestCanceledWarDeclaredLog);
      }

      protected override void OnFinalize()
      {
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();
    }

    public class LandLordNeedsManualLaborersIssueBehaviorTypeDefiner : SaveableTypeDefiner
    {
      public LandLordNeedsManualLaborersIssueBehaviorTypeDefiner()
        : base(810000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssue), 1);
        this.AddClassDefinition(typeof (LandLordNeedsManualLaborersIssueBehavior.LandLordNeedsManualLaborersIssueQuest), 2);
      }
    }
  }
}
